#include "localstorage.h"
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>

LocalStorage::LocalStorage() { }

LocalStorage::~LocalStorage()
{
    close();
}

LocalStorage& LocalStorage::instance()
{
    static LocalStorage inst;
    return inst;
}

bool LocalStorage::init(const QString& path)
{
    if (db_.isOpen())
        return true;

    db_ = QSqlDatabase::addDatabase("QSQLITE");
    db_.setDatabaseName(path);

    if (!db_.open()) {
        qWarning() << "Failed to open database:" << db_.lastError().text();
        return false;
    }

    // 提升读写速度
    QSqlQuery sq(db_);
    sq.exec("PRAGMA synchronous = OFF");
    sq.exec("PRAGMA journal_mode = MEMORY");

    // 创建DAO实例
    live_web_entry_dao_ = new LiveWebEntryDAO(db_);

    // 创建所有表
    return createTables();
}

void LocalStorage::close()
{
    // 释放DAO资源
    delete live_web_entry_dao_;
    live_web_entry_dao_ = nullptr;

    // 关闭数据库连接
    if (db_.isOpen()) {
        db_.close();
    }
}

LiveWebEntryDAO* LocalStorage::liveWebEntryDAO()
{
    return live_web_entry_dao_;
}

bool LocalStorage::createTables()
{
    if (live_web_entry_dao_ && !live_web_entry_dao_->createTable()) {
        return false;
    }

    return true;
}
